<?php
declare (strict_types=1);

namespace app\api\middleware;

use think\Response;
use think\facade\Cache;
use app\common\model\User;
use app\common\controller\Config;
use think\exception\HttpResponseException;

class Verify
{

    public function handle($request, \Closure $next)
    {
        $system = Cache::get('system');
        if (!$system) {
            $system = Config::lists();
            Cache::set('system', $system);
        }
        if ($system['web_site_close'] != 1) {
            $this->friendlyError(201, handleRichText($system['close_msg']));
        }
        $request->system = $system;

        $result = $this->verifyToken($request);
        if ($result['code'] !== 1) {
            $this->friendlyError($result['code'], $result['msg']);
        }
        $request->user = $result['result'];

        return $next($request);

    }

    protected function verifyToken($request)
    {
        $authorization = $request->header('Authorization', '');

        $token = preg_match('/^Bearer\s+(.*?)$/', $authorization, $matches) ? $matches[1] : '';
        if (!$token) return ['code' => 202, 'msg' => '请先登录后，在进行此操作！'];
        $user = User::where('token', $token)->find();
        if (empty($user)) return ['code' => 202, 'msg' => '请先登录后，在进行此操作！'];
        if ($user->is_lock) return ['code' => 202, 'msg' => '账号已锁定'];

        return ['code' => 1, 'result' => $user];
    }


    public function friendlyError($code, $message, $url = '', $type = '')
    {
        $result = [
            'code' => $code,
            'msg'  => $message,
        ];
        $response = Response::create($result, 'json');
        throw new HttpResponseException($response);
    }


}
